package com.example.codereview.util;

import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 多线程处理业务工具
 *
 * @author zl
 */
public class ThreadServiceUtil {

    public static final ExecutorService THREAD_POOL_EXECUTOR = new ThreadPoolExecutor(20, 80, 10, TimeUnit.SECONDS, new ArrayBlockingQueue<>(100));

    private ThreadServiceUtil(){}


    @FunctionalInterface
    public interface ServiceExecute<T>{

        void  execute(T t);
    }


    /**
     * 多线程处理业务
     */
    public static <T>void  execute(ServiceExecute<T> execute, List<T> list){
        //拆分
        CountDownLatch latch = new CountDownLatch(list.size());
        //执行后的结果申明
        for(T t : list){
            THREAD_POOL_EXECUTOR.execute(()->{
                try {
                    execute.execute(t);
                }catch (Exception e){
                }
                latch.countDown();
            });
        }
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }

}
